package server;
import java.io.IOException;
import java.io.InputStream;
import java.util.StringTokenizer;
/**
 * This class represents an HTTP Request
 * @author yariv zur
 */
public class Request {
	private String type = "";
	private String argument = "";
	private String host = "";
	private String contentType = "";
	private int contentLength = 0;
	private byte[] file;
	/**
	 * Constructor for Request class
	 * @param tok - tokenizer containing text portion of message
	 * @param is - InputStream containing the body of the message if it exists
	 * @throws IOException
	 */
	public Request(StringTokenizer tok, InputStream is) throws IOException{
		type = tok.nextToken();
		argument = tok.nextToken();
		while(tok.hasMoreTokens()){
			String temp = tok.nextToken();
			if(temp.equals("Host:")){
				host = tok.nextToken();
			}
			else if(temp.equals("Content-Type:")){
				contentType = tok.nextToken();
			}
			else if(temp.equals("Content-Length:")){
				contentLength = Integer.parseInt(tok.nextToken());
			}
		}
		if(contentLength > 0){ // the body is not empty
			file = new byte[contentLength];
			for(int i=0; i<file.length; i++){
				file[i] = (byte) is.read();
			}
			if(file.length != contentLength){
				throw new IOException("Could not read all the content from the message");
			}
		}
	}
	/**
	 * Method to return the resource id in the request's argument, if it exists
	 * @return the resource id
	 */
	public String getResourceName(){
		if(argument.contains("?rep=")){
			return argument.substring(argument.lastIndexOf('/')+1, argument.indexOf('?'));
		}
		else{
			return argument.substring(argument.lastIndexOf('/')+1);
		}
	}
	/**
	 * Method to return the representation id in the request's argument, if it exists
	 * @return the representation id
	 */
	public String getRepresentationName(){
		return this.argument.substring(argument.lastIndexOf("=")+1);
	}
	/**
	 * Getter for the request's type
	 * @return the request type
	 */
	public String getType(){
		return this.type;
	}
	/**
	 * Getter for the request's argument
	 * @return the request argument
	 */
	public String getArgument(){
		return this.argument;
	}
	/**
	 * Getter for the request's host
	 * @return the request host
	 */
	public String getHost(){
		return this.host;
	}
	/**
	 * Getter for the request's Content-Type header
	 * @return the request Content-Type
	 */
	public String getContentType(){
		return this.contentType;
	}
	/**
	 * Getter for the request's Content-Length header
	 * @return the request Content-Length
	 */
	public int getContentLength(){
		return this.contentLength;
	}
	/**
	 * Getter for the request's Content
	 * @return the request Content (message body)
	 */
	public byte[] getContent(){
		return this.file;
	}
}